/*--------------------------------------------------|
| jTree 1.1                                         |
|---------------------------------------------------|
|                                                   |
| Updated: 2007.04.11                               |
|--------------------------------------------------*/

// Node object
function Node(id, pid, name, className, url, title, target, icon, iconOpen, open) {
	this.id = id;
	this.pid = pid;
	this.name = name;
	this.url = url;
	this.title = title;
	this.target = target;
	this.icon = icon;
	this.iconOpen = iconOpen;
	this._isOpen = open || false;
	this._isSelect = false;
	this._lastId = false;
	this._hasChild = false;
	this._ai = 0;
	this._parentNode;
	this._className = (!className)?'jTreeNode':((className=='')?'jTreeNode':className);
	this._isChecked = false;
};

// Tree object
function jTree(objName, displayObjName) {
	this.imgBase = 'images/jtree/';
	this.config = {
		target					: null,
		folderLinks			: false,
		useSelection		: true,
		useCookies			: true,
		useLines				: true,
		useIcons				: false,
		useStatusText		: true,
		closeSameLevel	: false,
		inOrder					: false,
		useDelBtn       : false,
		useCheckbox     : false
	};
	this.checkbox = {
		falseSetParent  : false,
		trueSetParent 	: false,
		falseSetChild 	: false,
		trueSetChild 		: false,
		needChild 			: false
	};
	this.icon = {
		root				: this.imgBase+'base.gif',
		folder			: this.imgBase+'folder.gif',
		folderOpen	: this.imgBase+'folderopen.gif',
		node				: this.imgBase+'page.gif',
		empty				: this.imgBase+'empty.gif',
		line				: this.imgBase+'line.gif',
		join				: this.imgBase+'join.gif',
		joinBottom	: this.imgBase+'joinbottom.gif',
		joinTop   	: this.imgBase+'jointop.gif',
		plus				: this.imgBase+'plus.gif',
		plusBottom	: this.imgBase+'plusbottom.gif',
		plusTop	    : this.imgBase+'plustop.gif',
		minus				: this.imgBase+'minus.gif',
		minusBottom	: this.imgBase+'minusbottom.gif',
		minusTop	  : this.imgBase+'minustop.gif',
		nlPlus			: this.imgBase+'nolines_plus.gif',
		nlMinus			: this.imgBase+'nolines_minus.gif',
		del   			: this.imgBase+'del.gif'
	};
	this.obj = objName;
	this.displayObjName = displayObjName;
	this.aNodes = [];
	this.aIndent = [];
	this.root = new Node(-1);
	this.selectedNode = null;
	this.selectedFound = false;
	this.completed = false;
};

// Adds a new node to the node array
jTree.prototype.add = function(id, pid, name, className, url, title, target, icon, iconOpen, open) {
	this.aNodes[this.aNodes.length] = new Node(id, pid, name, className, url, title, target, icon, iconOpen, open);
};

// Open/close all nodes
jTree.prototype.openAll = function() {
	this.oAll(true);
};
jTree.prototype.closeAll = function() {
	this.oAll(false);
};

jTree.prototype.selectAll = function() {
	for(var i=0;i<this.aNodes.length;i++){
		this.aNodes[i]._isChecked = true;
	}
	this.refresh();
};

jTree.prototype.disSelectAll = function() {
	for(var i=0;i<this.aNodes.length;i++){
		this.aNodes[i]._isChecked = false;
	}
	this.refresh();
};

jTree.prototype.delNode = function(delId){
	if(eval("typeof("+this.obj+"_DelNode)")=="function"){
		eval(this.obj+"_DelNode("+delId+");");
	}
};

jTree.prototype.doClickCheckbox = function(id){
	var currenNode;
		for(var i=0; i<this.aNodes.length; i++) {
			if (this.aNodes[i].id == id){
				currenNode = this.aNodes[i];
				currenNode._isChecked = !currenNode._isChecked;
				break;
			}
		}
	if(currenNode._isChecked){
		if(this.checkbox.trueSetParent){
			this.setParent(currenNode.pid, currenNode._isChecked);
		}
		if(this.checkbox.trueSetChild){
			this.setChild(currenNode.id, currenNode._isChecked);
		}
	}else{
		if(this.checkbox.falseSetParent){
			this.setParent(currenNode.pid, currenNode._isChecked);
		}
		if(this.checkbox.falseSetChild){
			this.setChild(currenNode.id, currenNode._isChecked);
		}
		if(this.checkbox.needChild){
			this.setNeedChild(currenNode.pid, currenNode._isChecked);
		}
	}
	
	this.refresh();
};

jTree.prototype.setParent = function(id, check){
	var currenNode;
	for(var i=0; i<this.aNodes.length; i++){
		if (this.aNodes[i].id == id){
				currenNode = this.aNodes[i];
				if(currenNode.pid == this.root.id){
					return;
				}
				currenNode._isChecked = check;
				this.setParent(currenNode.pid, check);
				break;
		}
	}
};

jTree.prototype.setChild = function(id, check){
	var currenNode;
	for(var i=0; i<this.aNodes.length; i++){
		if (this.aNodes[i].pid == id){
				currenNode = this.aNodes[i];
				currenNode._isChecked = check;
				if(currenNode._hasChild){
					this.setChild(currenNode.id, check);
				}
		}
	}
};

jTree.prototype.setNeedChild = function(id, check){
	var currenNode;
	var tempNode;
	var noChild = true;
	for(var i=0; noChild && i<this.aNodes.length; i++){
		if (this.aNodes[i].id == id){
			currenNode = this.aNodes[i];
			if(currenNode.pid == this.root.id){
				return;
			}
		}
		if (this.aNodes[i].pid == id){
				tempNode = this.aNodes[i];
				if(tempNode._isChecked){
					noChild = false;
				}
		}
	}
	if(noChild){
		currenNode._isChecked = check;
		this.setNeedChild(currenNode.pid, currenNode._isChecked)
	}
};

jTree.prototype.refresh = function() {
	var obj = document.getElementById(this.displayObjName);
	if(obj){
		obj.innerHTML = this;
	}else{
		alert("["+this.displayObjName+"] object not found!")
	}
};

// Outputs the tree to the page
jTree.prototype.toString = function() {
	var str = '<div class="jTree">\n';
	if (document.getElementById) {
		if (this.config.useCookies) this.selectedNode = this.getSelected();
		str += this.addNode(this.root);
	} else str += 'Browser not supported.';
	str += '</div>';
	if (!this.selectedFound) this.selectedNode = null;
	this.completed = true;
	return str;
};

// Creates the tree structure
jTree.prototype.addNode = function(pNode) {
	var str = '';
	var n=0;
	if (this.config.inOrder) n = pNode._ai;
	for (n; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == pNode.id) {
			var currenNode = this.aNodes[n];
			currenNode._parentNode = pNode;
			currenNode._ai = n;
			this.setCS(currenNode);
			if (!currenNode.target && this.config.target) currenNode.target = this.config.target;
			if (currenNode._hasChild && !currenNode._isOpen && this.config.useCookies) currenNode._isOpen = this.isOpen(currenNode.id);
			if (!this.config.folderLinks && currenNode._hasChild) currenNode.url = null;
			if (this.config.useSelection && currenNode.id == this.selectedNode && !this.selectedFound) {
					currenNode._isSelect = true;
					this.selectedNode = n;
					this.selectedFound = true;
			}
			str += this.node(currenNode, n);
			if (currenNode._lastId) break;
		}
	}
	return str;
};

// Creates the node icon, url and text
jTree.prototype.node = function(node, nodeId) {
	var str = '<div class="'+node._className+'">' + this.indent(node, nodeId);
	if (this.config.useCheckbox) {
		if (this.root.id != node.pid) {
			str += '<input '+((node._isChecked)?'checked':'')+' type="checkbox" id="cb' + this.obj + nodeId + '" name="cb' + this.obj + '" value = "' + node.id +  '" onclick="javascript:' + this.obj + '.doClickCheckbox(' + node.id +  ');"/>';
		}
	}
	if (this.config.useIcons) {
		if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hasChild) ? this.icon.folder : this.icon.node);
		if (!node.iconOpen) node.iconOpen = (node._hasChild) ? this.icon.folderOpen : this.icon.node;
		if (this.root.id == node.pid) {
			node.icon = this.icon.root;
			node.iconOpen = this.icon.root;
		}
		str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._isOpen) ? node.iconOpen : node.icon) + '" alt="" />';
	}
	if (node.url) {
		str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._isSelect ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"';
		if (node.title) str += ' title="' + node.title + '"';
		if (node.target) str += ' target="' + node.target + '"';
		if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';
		if (this.config.useSelection && ((node._hasChild && this.config.folderLinks) || !node._hasChild))
			str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';
		str += '>';
	}
	else if ((!this.config.folderLinks || !node.url) && node._hasChild && node.pid != this.root.id)
		str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';
	str += node.name;
	if (node.url || ((!this.config.folderLinks || !node.url) && node._hasChild && this.root.id != node.pid)) str += '</a>';
	str += '</div>';
	if (node._hasChild) {
		str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._isOpen) ? 'block' : 'none') + ';">';
		str += this.addNode(node);
		str += '</div>';
	}
	this.aIndent.pop();
	return str;
};

// Adds the empty and line icons
jTree.prototype.indent = function(node, nodeId) {
	var str = '';
	if (this.root.id != node.pid) {
		if (this.config.useDelBtn) {
				str += '<span class="btnDel"><input type="button" value="Delete"   class="button1" name="Delete" onclick="javascript: ' + this.obj + '.delNode(' + node.id + ');" /></span>';
		}
		for (var n=0; n<this.aIndent.length; n++)
			str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
		(node._lastId) ? this.aIndent.push(0) : this.aIndent.push(1);
		if (node._hasChild) {
			str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
			if (!this.config.useLines) str += (node._isOpen) ? this.icon.nlMinus : this.icon.nlPlus;
			else str += ( (node._isOpen) ? ((node._lastId && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._lastId && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );
			str += '" alt="" /></a>';
		} else str += '<img src="' + ( (this.config.useLines) ? ((node._lastId) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
	} else{
		if (this.config.useDelBtn) {
				str += '<span class="btnDelTitle">Delete</span>';
		}
	}
	return str;
};

// Checks if a node has any children and if it is the last sibling
jTree.prototype.setCS = function(node) {
	var lastId;
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.id) node._hasChild = true;
		if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
	}
	if (lastId==node.id) node._lastId = true;
};

// Returns the selected node
jTree.prototype.getSelected = function() {
	var sn = this.getCookie('cs' + this.obj);
	return (sn) ? sn : null;
};

// Highlights the selected node
jTree.prototype.s = function(id) {
	if (!this.config.useSelection) return;
	var currenNode = this.aNodes[id];
	if (currenNode._hasChild && !this.config.folderLinks) return;
	if (this.selectedNode != id) {
		if (this.selectedNode || this.selectedNode==0) {
			eOld = document.getElementById("s" + this.obj + this.selectedNode);
			eOld.className = "node";
		}
		eNew = document.getElementById("s" + this.obj + id);
		eNew.className = "nodeSel";
		this.selectedNode = id;
		if (this.config.useCookies) this.setCookie('cs' + this.obj, currenNode.id);
	}
};

// Toggle Open or close
jTree.prototype.o = function(id) {
	var currenNode = this.aNodes[id];
	this.nodeStatus(!currenNode._isOpen, id, currenNode._lastId);
	currenNode._isOpen = !currenNode._isOpen;
	if (this.config.closeSameLevel) this.closeLevel(currenNode);
	if (this.config.useCookies) this.updateCookie();
};

// Open or close all nodes
jTree.prototype.oAll = function(status) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n]._hasChild && this.aNodes[n].pid != this.root.id) {
			this.nodeStatus(status, n, this.aNodes[n]._lastId)
			this.aNodes[n]._isOpen = status;
		}
	}
	if (this.config.useCookies) this.updateCookie();
};

// Opens the tree to a specific node
jTree.prototype.openTo = function(nId, bSelect, bFirst) {
	if (!bFirst) {
		for (var n=0; n<this.aNodes.length; n++) {
			if (this.aNodes[n].id == nId) {
				nId=n;
				break;
			}
		}
	}
	var currenNode=this.aNodes[nId];
	if (currenNode.pid==this.root.id || !currenNode._parentNode) return;
	currenNode._isOpen = true;
	currenNode._isSelect = bSelect;
	if (this.completed && currenNode._hasChild) this.nodeStatus(true, currenNode._ai, currenNode._lastId);
	if (this.completed && bSelect) this.s(currenNode._ai);
	else if (bSelect) this._sn=currenNode._ai;
	this.openTo(currenNode._parentNode._ai, false, true);
};

// Closes all nodes on the same level as certain node
jTree.prototype.closeLevel = function(node) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hasChild) {
			this.nodeStatus(false, n, this.aNodes[n]._lastId);
			this.aNodes[n]._isOpen = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
}

// Closes all children of a node
jTree.prototype.closeAllChildren = function(node) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.id && this.aNodes[n]._hasChild) {
			if (this.aNodes[n]._isOpen) this.nodeStatus(false, n, this.aNodes[n]._lastId);
			this.aNodes[n]._isOpen = false;
			this.closeAllChildren(this.aNodes[n]);		
		}
	}
}

// Change the status of a node(open or closed)
jTree.prototype.nodeStatus = function(status, id, bottom) {
	eDiv	= document.getElementById('d' + this.obj + id);
	eJoin	= document.getElementById('j' + this.obj + id);
	if (this.config.useIcons) {
		eIcon	= document.getElementById('i' + this.obj + id);
		eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
	}
	eJoin.src = (this.config.useLines)?
	((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):
	((status)?this.icon.nlMinus:this.icon.nlPlus);
	eDiv.style.display = (status) ? 'block': 'none';
};


// [Cookie] Clears a cookie
jTree.prototype.clearCookie = function() {
	var now = new Date();
	var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
	this.setCookie('co'+this.obj, 'cookieValue', yesterday);
	this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};

// [Cookie] Sets value in a cookie
jTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
};

// [Cookie] Gets a value from a cookie
jTree.prototype.getCookie = function(cookieName) {
	var cookieValue = '';
	var posName = document.cookie.indexOf(escape(cookieName) + '=');
	if (posName != -1) {
		var posValue = posName + (escape(cookieName) + '=').length;
		var endPos = document.cookie.indexOf(';', posValue);
		if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
		else cookieValue = unescape(document.cookie.substring(posValue));
	}
	return (cookieValue);
};

// [Cookie] Returns ids of open nodes as a string
jTree.prototype.updateCookie = function() {
	var str = '';
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n]._isOpen && this.aNodes[n].pid != this.root.id) {
			if (str) str += '.';
			str += this.aNodes[n].id;
		}
	}
	this.setCookie('co' + this.obj, str);
};

// [Cookie] Checks if a node id is in a cookie
jTree.prototype.isOpen = function(id) {
	var aOpen = this.getCookie('co' + this.obj).split('.');
	for (var n=0; n<aOpen.length; n++)
		if (aOpen[n] == id) return true;
	return false;
};

// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
};
if (!Array.prototype.pop) {
	Array.prototype.pop = function array_pop() {
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
};

